package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.DTO.BusinessAssignDto;
import com.crm.DTO.BusinessDto;
import com.crm.DTO.BusinessFollowDto;
import com.crm.common.exception.BusinessException;
import com.crm.common.result.TableDataInfo;
import com.crm.entity.Business;
import com.crm.entity.BusinessFollow;
import com.crm.entity.DictData;
import com.crm.entity.User;
import com.crm.entity.system.SysUser;
import com.crm.mapper.BusinessMapper;
import com.crm.mapper.BusinessUserMapper;
import com.crm.mapper.SystemMapper;
import com.crm.mapper.system.SysUserMapper;
import com.crm.service.BusinessService;
import com.crm.vo.BusinessFollowVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 2025/9/5 10:30
 * 注释：
 */
@Service
@Slf4j
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {

    /**
     * redisKey 记录商机回收过期提醒
     */
    private static final String WARN_TIME_BUSINESS_KEY = "warn_time:business";

    /**
     * 商机跟进记录类型为跟进
     */
    private static final String BUSINESS_FOLLOW_TYPE_TURE = "0";
    /**
     * 商机跟进记录类型为伪
     */
    private static final String BUSINESS_FOLLOW_TYPE_FALSE = "1";

    /**
     * 商机信息状态为处于公海
     */
    private static final String BUSINESS_STATUS_POOL = "3";

    /**
     * 数据字典类型为communication_point
     */
    private static final String DICT_TYPE_POINT = "communication_point";

    /**
     * loginUserName redisKey
     */
    private static final String LOGIN_USER_NAME = "loginUserName";

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private SystemMapper systemMapper;

    @Autowired
    private BusinessUserMapper businessUserMapper;


    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 商机列表
     *
     * @param businessDto
     * @return
     */
    @Override
    public TableDataInfo<Business> searchBusiness(BusinessDto businessDto) {

        Page<Business> page = new Page<>(businessDto.getPageNum(), businessDto.getPageSize());

        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<Business>()
                .eq(businessDto.getId() != null, Business::getId, businessDto.getId()) // 客户ID
                .eq(businessDto.getPhone() != null, Business::getPhone, businessDto.getPhone()) // 手机号
                .like(businessDto.getName() != null, Business::getName, businessDto.getName()) // 客户姓名
                .ge(businessDto.getBeginCreateTime() != null, Business::getCreateTime, businessDto.getBeginCreateTime()) // 创建时间
                .le(businessDto.getEndCreateTime() != null, Business::getUpdateTime, businessDto.getEndCreateTime()); // 更新时间

        Page<Business> pageData = businessMapper.selectPage(page, wrapper);

        TableDataInfo<Business> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(pageData.getTotal());
        tableDataInfo.setRows(pageData.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("操作成功");

        return tableDataInfo;

    }

    /**
     * 公海池列表
     *
     * @param businessDto
     * @return
     */
    @Override
    public TableDataInfo<Business> getBusiness(BusinessDto businessDto) {

        Page<Business> page = new Page<>(businessDto.getPageNum(), businessDto.getPageSize());

        LambdaQueryWrapper<Business> wrapper = new LambdaQueryWrapper<Business>()
                .eq(businessDto.getId() != null, Business::getId, businessDto.getId()) // 客户ID
                .eq(businessDto.getPhone() != null, Business::getPhone, businessDto.getPhone()) // 手机号
                .like(businessDto.getName() != null, Business::getName, businessDto.getName()) // 客户姓名
                .ge(businessDto.getBeginCreateTime() != null, Business::getCreateTime, businessDto.getBeginCreateTime()) // 创建时间
                .le(businessDto.getEndCreateTime() != null, Business::getUpdateTime, businessDto.getEndCreateTime()); // 更新时间

        Page<Business> pageData = businessMapper.selectPage(page, wrapper);

        TableDataInfo<Business> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(pageData.getTotal());
        tableDataInfo.setRows(pageData.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("操作成功");

        return tableDataInfo;
    }

    /**
     * 新增商机
     *
     * @param business
     * @return
     */
    @Override
    public boolean saveBusiness(Business business) {

        // 如果ID为空，手动设置
        if (business.getId() == null) {
            business.setId(System.currentTimeMillis()); // 使用时间戳作为ID
        }
        business.setStatus(1);
        return save(business);
    }

    /**
     * 根据商机编号查询商机跟进记录
     *
     * @param businessId 商机编号
     * @return 商机跟进记录列表
     */
    @Override
    public List<BusinessFollowVo> getBusinessFollowList(Long businessId) {
        //先获取商机跟进记录信息
        List<BusinessFollow> result = businessMapper.getBusinessFollowList(businessId);
        log.info("进行了数据库操作，返回了商机跟进记录结果：{}", result);
        if (CollectionUtils.isEmpty(result)) {
            log.info("没有数据，返回一个空集合");
            return new ArrayList<>();
        }
        List<BusinessFollowVo> response = new ArrayList<>();
        for (BusinessFollow list : result) {
            BusinessFollowVo vo = BeanUtil.copyProperties(list, BusinessFollowVo.class);
            //把沟通重点里面的字段提取出来
            if (!ObjectUtils.isEmpty(vo.getKeyItems())) {
                String[] keysItems = vo.getKeyItems().split(",");
                log.info("截取String：{}", keysItems);
                // 将 keys 数组转为 Set 提升查询效率
                Set<String> keyItemsSet = new HashSet<>(Arrays.asList(keysItems));
                log.info("转换为Set：{}", keyItemsSet);
                //去数据字典查沟通重点相关的内容，封装进一个字符串集合
                List<DictData> dictDataList = systemMapper.getDictDataByDictType(DICT_TYPE_POINT);
                log.info("查询数据字典类型为communication_point的数据内容：{}", dictDataList);
                List<String> keysArray = dictDataList.stream()
                        .filter(item -> keyItemsSet.contains(item.getDictType()))    //根据keyItemsSet去筛选需要的字段
                        .map(DictData::getDictLabel)                                 //提取dictDataList其中的dictLabel字段
                        .collect(Collectors.toList());                               //放进字符串集合中
                vo.setKeys(keysArray);
                log.info("封装进了vo中：{}", vo);
                response.add(vo);
            }
        }
        log.info("封装进了集合中：{}", response);
        return response;
    }


    /**
     * 新增商机跟进记录
     *
     * @param dto
     */
    @Override
    public void addBusinessRecord(BusinessFollowDto dto) {
        // 新增商机跟进记录。将BusinessFollowDto数据复制到Business实体并更新商机信息；
        Business business = new Business();
        BeanUtils.copyProperties(dto, business);
        businessMapper.updateById(business);
        //再新增商机线索表,然后将BusinessFollowDto数据复制到BusinessFollow实体，设置商机ID和跟进类型，最后插入商机跟进记录。
        BusinessFollow businessFollow = BeanUtil.copyProperties(dto, BusinessFollow.class);
        businessFollow.setBusinessId(Long.valueOf(dto.getBusinessId()));
        businessFollow.setType(BUSINESS_FOLLOW_TYPE_TURE);
        log.info("复制商机跟进记录信息：{}", businessFollow);
        businessMapper.addBusinessFollow(businessFollow);
        log.info("新增了商机跟进记录信息");

    }

    /**
     * 商机分配
     *
     * @param businessAssignDto
     */
    @Override
    public void AllocationBusiness(BusinessAssignDto businessAssignDto) {

        //从businessAssignDto中获取用户ID和商机ID列表，再根据用户ID查询用户信息，然后遍历商机ID列表，为每个商机设置所属用户ID和负责人名称，并更新数据库中的商机记录。
        Long userId = businessAssignDto.getUserId();
        User user = businessUserMapper.selectById(userId);
        String userName = user.getUserName();
        List<Long> ids = businessAssignDto.getIds();
        for (Long id : ids) {
            LambdaUpdateWrapper<Business> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Business::getId, id);
            updateWrapper.set(Business::getUserId, userId);
            updateWrapper.set(Business::getOwner, userName);
            super.update(updateWrapper);
        }

    }

    /**
     * 分配
     *
     * @param ownerId    现在的负责人ID
     * @param transferId 要分配的用户ID
     * @return
     */
    @Override
    public void assignment(Long ownerId, Long transferId) {
        //参数校验
        if (ownerId == null || transferId == null) {
            throw new BusinessException("参数错误");
        }
        if (ownerId.equals(transferId)) {
            throw new BusinessException("不能转让给自己");
        }
        //获取当前拥有有人
        SysUser owner = sysUserMapper.selectUserById(ownerId);
        //转派目标
        SysUser transfer = sysUserMapper.selectUserById(transferId);
        //获取当前拥有人 全部 商机
        List<Business> businesses = super.list(new LambdaQueryWrapper<Business>().eq(
                Business::getOwner, owner.getUserName()));
        businesses.forEach(business -> {
            business.setOwner(transfer.getUserName());
        });
        super.updateBatchById(businesses);
    }
}
